package com.es.util;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.NodeSelector;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

public class ClientBuilder {

    private static final String CLUSTER_HOSTNAME_PORT = "localhost:9200";

    public static RestClientBuilder restClientBuilder(){
        String[] hosts = CLUSTER_HOSTNAME_PORT.split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length];

        for(int i=0; i<hosts.length; i++) {
            String[] host = hosts[i].split(":");
            httpHosts[i] = new HttpHost(host[0], Integer.parseInt(host[1]), "http");
        }
        RestClientBuilder builder = RestClient.builder(httpHosts);

        // region设置请求头，避免每个请求都必须指定
//        Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
//        builder.setDefaultHeaders(defaultHeaders);

        // 设置节点发生故障时收到通知
        builder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(Node node) {
                super.onFailure(node);
            }
        });

        // 设置默认修改请求配置的函数 如请求超时
        builder.setRequestConfigCallback(
                new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(
                            RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setSocketTimeout(10000);
                    }
                });

        builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);

        return builder;
    }

}
